<template>
  <div class="app-container">
    <div class="app-container_conter">
    <el-form :model="queryParams" ref="queryForm" style="display: flex;justify-content: space-between;align-items: flex-end" :inline="true"
             v-show="showSearch" label-width="110px">
      <div style="display: flex;flex-flow: wrap">
      <el-form-item label="证件号码" prop="idCardNo" >
        <el-input v-model="queryParams.idCardNo" placeholder="请输入证件号码" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="保单号码" prop="insureNo" >
        <el-input v-model="queryParams.insureNo" placeholder="请输入保单号码" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="时间筛选" prop="insuranceTime" >
        <el-date-picker
            v-model="queryParams.insuranceTime"
            type="month"
            placeholder="选择月"
            value-format="yyyy-MM"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="投保人"  prop="name1">
        <el-input v-model="queryParams.name1" placeholder="请输入投保人" clearable size="small"
        />
      </el-form-item>
      <el-form-item label="被保险人"  prop="name2">
        <el-input v-model="queryParams.name2" placeholder="请输入被保险人" clearable size="small"
        />
      </el-form-item>
      </div>
      <div>
      <el-form-item  style="width: 150px;text-align: right">
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info"  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      </div>
    </el-form>


    <el-table v-loading="loading" :data="insureEliList" @selection-change="handleSelectionChange"  :header-cell-style="tableHeaderColor">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="保单编号" align="center" prop="id"/>-->
      <el-table-column label="保单号" align="center" prop="insure_no" fixed min-width="180px"/>
<!--      <el-table-column label="投保人" align="center" prop="name1"/>-->
<!--      <el-table-column label="投保人电话" align="center" prop="phone1"/>-->
      <!--      <el-table-column label="投保人邮编" align="center" prop="commAddrAndPostcode1" />-->
      <!--      <el-table-column label="投保人邮箱" align="center" prop="email1" />-->
      <el-table-column label="被保险人" align="center" prop="name2" min-width="150px"/>
      <el-table-column label="被保险人电话" align="center" prop="phone2" min-width="120px"/>
      <!--      <el-table-column label="总保险费" align="center" prop="sinsurance_fee_count" />-->
      <el-table-column label="保险起期" align="center" prop="insurance_time_start" min-width="120px"/>
      <el-table-column label="保险止期" align="center" prop="insurance_time_end" min-width="120px"/>
      <el-table-column label="创建时间" align="center" prop="create_time" min-width="150px"/>
      <!--      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>-->
      <el-table-column label="操作" align="center" fixed="right" min-width="120px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              @click="handleWorld(scope.row)"
              v-hasPermi="['insurance:insureEli:exportProve']"
          >导出
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    </div>
    <pagination
        style="background: transparent"
        v-show=" total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
    <el-dialog
        title="实际用工单位"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <el-row>
        <el-col :span="6">
          <div>实际用工单位</div>
        </el-col>
        <el-col :span="18">
          <el-select v-model="queryParams3.company" placeholder="请搜索实际用工单位" :filterable="true" :reserve-keyword="true"
                     style="width:280px" :filter-method="search" v-loadmore="loadMore">
            <el-option
                v-for="item in options"
                :key="item.company"
                :label="item.company"
                :value="item.company">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getExport">导出</el-button>
       </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInsureEli,
  exportInsureEli,
  exportWord,
} from "@/api/insurance/insureEli";
import {
  exportProve,
  getExistInsureNoList,
  insure_export,
  getExistInsureNoList1,
  batchExportProve,
  get_insure_company
} from "@/api/insurance/guarantee"
import Template from "../../base/template/index";
import {listUser} from "@/api/insurance/user";

export default {
  name: "InsureEli",
  components: {
    Template
  },
  data() {
    return {
      value1: '',
      options: [],
      value: '',
      show: true,//判断上传图片显示隐藏
      dialogVisible: false,
      Policy: {
        //  投保id
        id: '',
        insureNo: '',//保单号
      },
      rules: {
        insureNo: [
          {required: true, message: '请输入保单号', trigger: 'blur'},
        ]
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 雇主责任险保单表格数据
      insureEliList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      title1: '',
      //状态字典
      statusOptions: [],
      // 查询参数用户参数
      queryParams1: {
        pageNum: 1,
        user_id: '',
        pageSize: 10,
        idCardNo: null,
        insureNo: null,
        name1: null,//投保人
        name2: null,//被投保人
        insuranceTime: '',//时间筛选
        company: null,//用工单位
      },
      rules1: {
        idCardNo: [
          {required: true, message: '请输入证件号码', trigger: 'blur'}
        ]
      },
      // 查询参数
      queryParams: {
        user_id: '',
        pageNum: 1,
        pageSize: 10,
        idCardNo: null,
        insureNo: null,
        name1: null,//投保人
        name2: null,//被投保人
        insuranceTime: '',//时间筛选
        employer: null,//用工单位
      },
      queryParams2: {
        insure_id: '',//保单id
        user_id: '',// 用户id
        role_id: '',// 权限id
        company: '',// 公司名称
      },
      queryParams3: {
        insure_id: '',//保单id
        user_id: '',// 用户id
        role_id: '',// 权限id
        company: '',// 公司名称
      },
      //  保单信息
      infoUser: {}
    };
  },

  created() {
    this.queryParams.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    this.queryParams1.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    this.queryParams2.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    this.queryParams3.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    var user = JSON.parse(localStorage.getItem('userInfo'));
    if (user.roles.length != 0) {
      this.queryParams2.role_id = user.roles[0].roleId;
      this.queryParams3.role_id = user.roles[0].roleId;
    }
    // console.log('user', user);
    this.getList();
    this.getDicts("insure_eli_status").then(res => {
      this.statusOptions = res.data;
    })
  },
  methods: {
    tableHeaderColor({ rowIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #304156;color: #fff;font-weight: 400;font-family: Microsoft YaHei;'
      }
    },
    search(e) {
      this.queryParams2.company = e
      // console.log('34345', e)
      // this.queryParams1.keyWord=e;
      // this.getnsureNoList();
      this.getCompany();
    },
    getCompany() {
      // console.log('queryParams2', this.queryParams2)
      get_insure_company(this.queryParams2).then(res => {
        this.options = res.data
        // console.log('res用工单位', res)
      })
    },
    //选择保单时下拉刷新加载数据
    loadMore() {
      this.queryParams1.pageSize += 10
      // console.log('2342353',this.queryParams1)
      this.getnsureNoList();
    },
    // 点击搜索，搜索对应的证件号码
    getSearch(queryParams1) {
      this.queryParams.pageNum = 1;
      // this.queryParams.idCardNo=this.form.idCardNo
      // console.log('queryParams1', this.queryParams1);
      this.$refs[queryParams1].validate((valid) => {
        if (valid) {
          listUser(this.queryParams1).then(res => {
            // console.log('res用户', res);
            if (res.rows.length != 0) {

              // this.show = true;
              // this.form.userId = res.rows[0].id;
              // this.form.name = res.rows[0].name;
              // this.form.idCardNo = res.rows[0].idCardNo;
              // this.form.actualUnit = res.rows[0].company;
              this.$router.push({
                path: '/business/applicationFiling/index',
              })
              this.$store.commit('Insure_User', res.rows[0]);
              this.$store.commit('Info_Insure', this.infoUser);

            } else {
              this.$message({
                message: '暂时没有这个人，请重新搜索查询',
                type: 'warning'
              })
              this.show = false
            }

          })
        }
      })
    },
    /** 查询雇主责任险保单列表 */
    getList() {
      // console.log('查询')
      this.loading = true;
      // console.log('queryParamsqw', this.queryParams)
      getExistInsureNoList1(this.queryParams).then(response => {
        this.insureEliList = response.data.rows;
        // console.log('insureEliList', this.insureEliList)
        this.insureEliList.forEach(v => {
          // console.log(v.nsurance_time_start)
          v.insurance_time_start = v.insurance_time_start.substring(0, 10);
          v.insurance_time_end = v.insurance_time_end.substring(0, 10)
        })

        this.total = response.data.total;
        this.loading = false;
      });
    },
    //导出
    getExport() {
      var that = this
      this.$confirm('是否确认将数据导出word?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        const loading = that.$loading({
          lock: true,
          text: '请耐心等待正在导出数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // console.log('ididd', that.queryParams3)
        // var obj={
        //   insure_id:row.id
        // }
        insure_export(that.queryParams3).then(response => {
          that.dialogVisible = false
          // console.log('response', response);
          loading.close();
          // that.$message({
          //   message: '导出数据成功!',
          //   type: 'success'
          // });
          let link = document.createElement('a'); // 创建a标签
          link.style.display = 'none';
          let objectUrl = response.data;
          link.href = objectUrl;
          link.click();
          that.msgSuccess(response.msg);

          // that.download(response.msg);
        })
      }).then(response => {
      })
    },
    //根据id将保单导出pdf
    handleWorld(row) {
      console.log('row', row)
      this.queryParams2.insure_id = row.id;
      this.queryParams3.insure_id = row.id;
      this.dialogVisible = true

    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        insureNo: null,
        name1: null,
        phone1: null,
        commAddrAndPostcode1: null,
        email1: null,
        name2: null,
        phone2: null,
        commAddrAndPostcode: null,
        email2: null,
        nature2: null,
        industry: null,
        address2: null,
        businessScope2: null,
        staffCount2: null,
        seniorDescription: null,
        generalDescription: null,
        isELI: null,
        isLossEli: null,
        eliDesc: null,
        isII: null,
        isLossIi: null,
        iiDesc: null,
        isTrain: null,
        trainingTime: null,
        isHaveMedicalStaff: null,
        medicalStaffCount: null,
        hospitalDistance: null,
        hospitalName: null,
        isJoinMi: null,
        descriptionMi: null,
        compPrincipleAndLimit: null,
        otherDescription: null,
        casualtiesFeeLimit: null,
        medicalFeeLimit: null,
        legalFeeLimit: null,
        liabilityLimit: null,
        deductible: null,
        insuranceRate: null,
        insuranceTimeStart: null,
        insuranceTimeEnd: null,
        insuranceFeeCount: null,
        payTime: null,
        solution: null,
        seal: null,
        signingTime: null,
        agent: null,
        underwriting: null,
        signPolicyholder: null,
        signPolicyholderTime: null,
        createTime: null,
        updateTime: null,
        insUserIds: null,
        userPath: null,
        status: "0"
      };
      this.resetForm("form");
    },
    //状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // console.log('value1', this.value1);
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      const ids = this.ids
      var that = this;

      console.log('ids', this.ids)
      this.$confirm('是否确认导出所有雇主责任险保单数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        if (ids.length != 0) {
          // const loading = that.$loading({
          //   lock: true,
          //   text: '请耐心等待正在导出数据...',
          //   spinner: 'el-icon-loading',
          //   background: 'rgba(0, 0, 0, 0.7)'
          // });
          // console.log('ids23', that.ids)
          batchExportProve(ids).then(response => {
            // loading.close();
            // console.log('response12', response)
            let blob = new Blob([response], {type: 'application/zip'}); //type为所需要下载的文件格式，以xls文件为例
            // console.log('blob', blob)
            // console.log('blob1:',blob.size)
            // 浏览器兼容，Google和火狐支持a标签的download，IE不支持
            if (window.navigator && window.navigator.msSaveBlob) {
              //IE浏览器、微软浏览器
              /* 经过测试，微软浏览器Microsoft Edge下载文件时必须要重命名文件才可以打开，
                IE可不重命名，以防万一，所以都写上比较好 */
              window.navigator.msSaveBlob(blob, '文件.xls');
            } else {
              //其他浏览器
              let link = document.createElement('a'); // 创建a标签
              link.style.display = 'none';
              let objectUrl = URL.createObjectURL(blob);
              link.href = objectUrl;
              link.click();
              URL.revokeObjectURL(objectUrl);
            }

          })
        } else {
          that.$message.error('请选择要导出的数据!');
        }
      }).then(response => {
        // console.log('response', response)
        // this.download(response.msg);
      })
    }
  }
};
</script>
<style scoped>
.app-container_conter{
  background: #F8FBFF;
  padding:30px;
  border-radius: 10px;
  box-sizing: border-box;
}
</style>

